import sqlite3
import hashlib
import uuid
from datetime import datetime


class User:
    def __init__(self, db_name="users.db"):
        self.conn = sqlite3.connect(db_name)
        self.create_tables()

    def create_tables(self):
        cursor = self.conn.cursor()
        # 用户表
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id TEXT PRIMARY KEY,
            username TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL,
            email TEXT UNIQUE NOT NULL,
            role TEXT NOT NULL DEFAULT 'user',
            created_at TIMESTAMP NOT NULL,
            last_login TIMESTAMP
        )
        ''')
        self.conn.commit()

    def hash_password(self, password):
        return hashlib.sha256(password.encode()).hexdigest()

    def register(self, username, password, email, role='user'):
        try:
            user_id = str(uuid.uuid4())
            hashed_pwd = self.hash_password(password)
            now = datetime.now().isoformat()

            cursor = self.conn.cursor()
            cursor.execute('''
            INSERT INTO users (id, username, password, email, role, created_at)
            VALUES (?, ?, ?, ?, ?, ?)
            ''', (user_id, username, hashed_pwd, email, role, now))
            self.conn.commit()
            return {"success": True, "user_id": user_id}
        except sqlite3.IntegrityError as e:
            return {"success": False, "error": "用户名或邮箱已存在"}
        except Exception as e:
            return {"success": False, "error": str(e)}

    def login(self, username, password):
        try:
            hashed_pwd = self.hash_password(password)
            cursor = self.conn.cursor()
            cursor.execute('''
            SELECT id, username, role FROM users 
            WHERE username = ? AND password = ?
            ''', (username, hashed_pwd))
            user = cursor.fetchone()

            if user:
                # 更新最后登录时间
                now = datetime.now().isoformat()
                cursor.execute('''
                UPDATE users SET last_login = ? WHERE id = ?
                ''', (now, user[0]))
                self.conn.commit()
                return {
                    "success": True,
                    "user_id": user[0],
                    "username": user[1],
                    "role": user[2]
                }
            return {"success": False, "error": "用户名或密码错误"}
        except Exception as e:
            return {"success": False, "error": str(e)}

    def get_user_info(self, user_id):
        try:
            cursor = self.conn.cursor()
            cursor.execute('''
            SELECT username, email, role, created_at, last_login 
            FROM users WHERE id = ?
            ''', (user_id,))
            user = cursor.fetchone()

            if user:
                return {
                    "success": True,
                    "username": user[0],
                    "email": user[1],
                    "role": user[2],
                    "created_at": user[3],
                    "last_login": user[4]
                }
            return {"success": False, "error": "用户不存在"}
        except Exception as e:
            return {"success": False, "error": str(e)}

    def update_user_info(self, user_id, **kwargs):
        try:
            updates = []
            params = []

            if 'email' in kwargs:
                updates.append("email = ?")
                params.append(kwargs['email'])

            if 'password' in kwargs:
                updates.append("password = ?")
                params.append(self.hash_password(kwargs['password']))

            if not updates:
                return {"success": False, "error": "没有需要更新的信息"}

            params.append(user_id)
            query = f"UPDATE users SET {', '.join(updates)} WHERE id = ?"

            cursor = self.conn.cursor()
            cursor.execute(query, params)
            self.conn.commit()

            return {"success": True}
        except sqlite3.IntegrityError:
            return {"success": False, "error": "邮箱已被使用"}
        except Exception as e:
            return {"success": False, "error": str(e)}

    def close(self):
        self.conn.close()